package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"mime"
	"net/http"
	"path/filepath"
	"time"
)

const endpoint = "117.27.231.246:9000"
const accessKey = "EoSYgm5gu5P9BQdIXzsp"
const secretKey = "42ILntEI4eirSTOSQJHy1f7C4nK0eeVomK6SBYtS"
const bucketName = "123"

func Upload(c *gin.Context) {
	fileHeader, _ := c.FormFile("file")
	client, _ := minio.New(endpoint, &minio.Options{
		Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
	})
	open, _ := fileHeader.Open()
	location, _ := time.LoadLocation("Asia/Shanghai")
	noe := time.Now().In(location).Truncate(time.Second)
	timeStr := noe.Format("20060102150405")
	ext := filepath.Ext(fileHeader.Filename)
	contentType := mime.TypeByExtension(ext)
	objectName := fmt.Sprintf("%s/%s", timeStr, fileHeader.Filename)
	client.PutObject(c, bucketName, objectName, open, fileHeader.Size, minio.PutObjectOptions{ContentType: mime.TypeByExtension(contentType)})
	url := fmt.Sprintf("http://%s/%s/%s", endpoint, bucketName, objectName)
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "图片发送成功",
		"url":     url,
	})
}
